package cat.joronya.supermanager.privateleague;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.service.SupermanagerServiceHelper;

/**
 * Activitat per llistat les lligues privades de l'usuari.
 * @author pol
 */
public class PrivateLeagueListActivity extends ListActivity 
{
	// pel Log
	private static final String TAG = "supermanager";
	
	/**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
            Supermanager.PrivateLeague._ID, 			// 0
            Supermanager.PrivateLeague.ID_PRIV, 		// 1
            Supermanager.PrivateLeague.NAME, 			// 2
            Supermanager.PrivateLeague.NUMBER_OF_TEAMS, // 3
            Supermanager.PrivateLeague.MODIFIED_DATE 	// 4
    };
    
	/** 
	 * Called when the activity is first created. 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.private_league_list);
    
		// amaguem el ProgressBar
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.private_league_list_loading);
        progressBar.setVisibility(View.INVISIBLE);
        
        // If no data was given in the intent, then use our default content provider.
        Intent intent = getIntent();
        Uri plUri = getIntent().getData();
        if( plUri == null) {
        	plUri = Supermanager.PrivateLeague.CONTENT_URI;
            intent.setData(Supermanager.PrivateLeague.CONTENT_URI);
        }
	
        Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null, null,
                Supermanager.PrivateLeague.DEFAULT_SORT_ORDER);
        
		// Used to map notes entries from the database to views
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
        		R.layout.private_league_list_row, 
        		cursor,
                new String[] { Supermanager.PrivateLeague.NAME, 
        					   Supermanager.PrivateLeague.NUMBER_OF_TEAMS }, 
        		new int[] { R.id.private_league_list_row_name,
        					R.id.private_league_list_row_members });
        setListAdapter(adapter);
	}
	
	/**
	 * Al clicar una lliga privada anem al detall.
	 */
	protected void onListItemClick (ListView l, View v, int position, long id)
	{
		Log.d(TAG,"veient detall de lliga privada amb _id: "+id);
		// mostrem l'activitat del detall de lliga
		startActivity(new Intent(this,PrivateLeagueActivity.class)
			.setData(Supermanager.PrivateLeagueTeam.CONTENT_URI)
			.putExtra("cat.joronya.supermanager.privateleague.id", id));
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.private_league_list, menu);
        return true;
    }

	@Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle item selection
		switch (item.getItemId()) 
		{
			case R.id.refresh:
				Log.d(TAG,"refreshing private league list");
				// mostrem el ProgressBar
		        ProgressBar progressBar = (ProgressBar) findViewById(R.id.private_league_list_loading);
		        progressBar.setVisibility(View.VISIBLE);
		        
				// cridar refresh al REST method
				SupermanagerServiceHelper.getInstance(this).getPrivateLeagues(handler);
				break;
		}

		return true;
    }
	
    private Handler handler = new Handler() 
    { 
        @Override 
        public void handleMessage(Message msg)
        { 
            //get data from msg 
            int status = msg.getData().getInt(Supermanager.STATUS_MESSAGE);
            Log.d(TAG, "PrivateLeagueListActivity received status: "+status);
            
            // TODO: check auth error, connectivity error, closed error, other error
            if( status == Supermanager.PRIVATE_LEAGUES_PARSED_OK )
            {
            	// amaguem el ProgressBar
		        ProgressBar progressBar = (ProgressBar) findViewById(R.id.private_league_list_loading);
		        progressBar.setVisibility(View.INVISIBLE);
		        
            	Toast.makeText(getApplicationContext(), 
            			R.string.private_league_list_toast_refresh_done, 
            			Toast.LENGTH_SHORT).show();
            }
            
            super.handleMessage(msg); 
        } 
    };

}
